"""
    Contains utility class for migration.
"""

from sqlobject import SQLObject
from sqlobject.col import IntCol

from mnemoply.model.hub import __connection__
from mnemoply.utils import read_file

class ModelVersion(SQLObject):
    """
        Class contains version field.
        Need for migrations.
    """

    versionField = IntCol(notNull=True)

    title = property(lambda self: str(self.versionField))

    @classmethod
    def setDBVersion(cls, new):
        """
            Update DB table and set or create row with new model version.
        """

        if cls.select().count() > 0:
            cls.select()[0].versionField = new
        else:
            cls(versionField=new)

    @classmethod
    def getDBVersion(cls):
        """
            Get current model version from DB.
            If table ontains more than 1 row, returns 0 as result.
        """

        rows = list(cls.select())

        if len(rows) > 0:
            return rows[0].versionField
        else:
            return 0

    @classmethod
    def getFSVersion(cls):
        """
            Get current model version from spesial plain text file.
        """

        return int(read_file('mnemoply/model/version'))

